package com.yxt.ui;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;

import com.yxt.common.download.MultiThreadDownload;
import com.yxt.common.sys.CommConstant;
import com.yxt.common.ui.ActivityStackControlUtil;
import com.yxt.common.ui.NormalTableAdapter;
import com.yxt.common.ui.NormalTableAdapter.TableCell;
import com.yxt.common.ui.NormalTableAdapter.TableRow;
import com.yxt.common.zip.ZipUtil;
import com.yxt.exception.InternetException;
import com.yxt.exception.RemoteServerException;
import com.yxt.exception.XmlParserException;
import com.yxt.model.Knowledge;
import com.yxt.service.KnowledgeService;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.Window;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;

/**
 * 知识库一览
 * @author crayman
 */
public class KnowledgeListActivity extends Activity {
	private int cols = 1;
	private int height = 40;
	private int color = Color.WHITE;
	private TextView lblTitle;
	private List<String> knowtypes = new ArrayList<String>();
	private KnowledgeService service = new KnowledgeService(KnowledgeListActivity.this);
	private ProgressDialog dialog;
	
	private void downloadKnowledge() {
		dialog = new ProgressDialog(this);
		dialog.setTitle("知识库");
		dialog.setMessage("数据下载中,请稍候...");
		dialog.show();
		final Handler hanlder = new Handler(){
			public void handleMessage(Message msg)	{
				if (msg.what == 1)	{
					if (knowtypes.size() > 0 ) {
						fillKnowledgeList(knowtypes.get(0));
					}
				}
			}
		};
		
		new Thread(){
			public void run(){
				Looper.prepare();
				try {
					InputStream inputStream = getInputStream();
					SAXParserFactory factory = SAXParserFactory.newInstance();
					SAXParser parser = factory.newSAXParser();
					parser.parse(inputStream, new KnowledgeHandler());
				}  catch (IOException e) {
					dialog.cancel();
					throw new InternetException("");
				} catch (ParserConfigurationException e){
					dialog.cancel();
					throw new XmlParserException("");
				} catch(SAXException ex) {
					dialog.cancel();
					throw new XmlParserException("");
				}
				Message m = new Message();
				m.what = 1;
				hanlder.sendMessage(m);
				Looper.loop();
			};

		}.start();
	}

	private InputStream getInputStream() throws IOException {
		Intent intent = getIntent();
		String itemId = intent.getStringExtra("itemId");
		Map<String, String> menu = CommConstant.Main.FUNCTIONS.get(CommConstant.Main.CURRENT_TEMPLATE_CODE).get(itemId);
		String server = menu.get("server");
		InputStream input = null;
		if (CommConstant.DEBUG_MODEL) {
			input = new FileInputStream(CommConstant.Config.DEFAULT_PHONE_DIR + CommConstant.Config.XML_LOCATION + "knowledge.xml");
		} else {
			URL url = new URL(server + "Knowledge/Download.aspx?iphoneid=" + CommConstant.Main.CURRENT_IPHONE_CODE + "&version=" + CommConstant.Main.CURRENT_IPHONE_VERSION + "&areacode=" + CommConstant.Main.CURRENT_AREA_CODE + "&rvnm="+CommConstant.Main.CURRENT_RIVER_CODE);
			HttpURLConnection conn = (HttpURLConnection) url.openConnection();
			conn.setReadTimeout(CommConstant.Config.DEFAULT_TIMEOUT);
			conn.connect();
			input = conn.getInputStream();
		}
		return input;
	}

	private class KnowledgeHandler extends DefaultHandler {		
		public void startDocument() throws SAXException {
			super.startDocument();
			service.deleteKnowledge();
		}

		public void startElement(String uri, String localName, String qName,
				Attributes attrs) throws SAXException {
			String type = attrs.getValue("type");
			if ("fileinfo".equals(localName)) {
				Knowledge knowledge = new Knowledge();
				knowledge.setId(attrs.getValue("id"));
				knowledge.setName(attrs.getValue("title"));
				knowledge.setFilename(attrs.getValue("title"));
				knowledge.setLocpath(attrs.getValue("url"));
				knowledge.setOrderid(attrs.getValue("orderby"));
				knowledge.setType(attrs.getValue("type"));
				service.saveKnowledge(knowledge);
				if (!knowtypes.contains(type)){
					knowtypes.add(type);
				}
			} else if ("filedata".equals(localName)){
				String url = attrs.getValue("url");
				String file = url.substring(url.lastIndexOf("/")+1);
				try{
					MultiThreadDownload download = new MultiThreadDownload(url,CommConstant.Config.DEFAULT_PHONE_DIR+CommConstant.Config.HTML_LOCATION,file);
					download.start();
					while(true){
						if(download.getDownloadPercent() >= 100)
							break;
					}				
					ZipUtil.unZipFolder(CommConstant.Config.DEFAULT_PHONE_DIR+CommConstant.Config.HTML_LOCATION+file, CommConstant.Config.DEFAULT_PHONE_DIR+CommConstant.Config.HTML_LOCATION);					
				}catch(Exception ex){	
					ex.printStackTrace();
				}
			}else if ("message".equals(localName)) {
				throw new RemoteServerException(attrs.getValue("info"));
			}
		}
	}

	private void initComponent() {
		Button btnBackHome = (Button) findViewById(R.id.btnBackHome);
		lblTitle = (TextView) findViewById(R.id.lblTitle);

		btnBackHome.setOnClickListener(new OnClickListener() {
			public void onClick(View arg0) {
				Intent intent = new Intent();
				intent.setClass(getApplicationContext(), MainActivity.class);
				startActivity(intent);
			}
		});
		List<String> types = service.getKnowledgeType();
		if (types.size() == 0) {
			downloadKnowledge();
		} else {
			knowtypes.addAll(types);
		}
		if (knowtypes.size() > 0 ) {
			fillKnowledgeList(knowtypes.get(0));
		}
	}

	private void fillKnowledgeList(String title) {
		lblTitle.setText(title);
		List<TableRow> table = new ArrayList<TableRow>();
		int[] width = { 250 };
		List<Knowledge> list = service.getKnowledgesByType(title);
		for (int i = 0; i < list.size(); i++) {
			Knowledge knowledge = list.get(i);
			// 每行的数据
			TableCell[] cells = new TableCell[cols];
			cells[0] = new TableCell(knowledge.getName(), width[0], height, color, TableCell.STRING,new TextItemOnClickListener(knowledge.getLocpath(),knowledge.getName(),knowledge.getType()));
			table.add(new TableRow(cells));
		}
		NormalTableAdapter tableAdapter = new NormalTableAdapter(this, table);
		ListView lstWaterStation = (ListView) findViewById(R.id.lstKnowledgeList);
		lstWaterStation.setAdapter(tableAdapter);
	}

	/**
	 * 创建底部菜单
	 * */
	public boolean onCreateOptionsMenu(Menu menu) {
		super.onCreateOptionsMenu(menu);
		for(int i = 0; i < knowtypes.size(); i++) {
			menu.add(0, Menu.FIRST + i, i, knowtypes.get(i));
		}
		menu.add(0, 100, 100, R.string.menu_download);

		return super.onCreateOptionsMenu(menu);
	}

	/**
	 * 点击底部菜单项时的处理
	 */
	public boolean onOptionsItemSelected(MenuItem item) {
		if (item.getItemId() == 100) {
			downloadKnowledge();
		} else {
			String title = item.getTitle().toString();
			fillKnowledgeList(title);
		}
		return super.onOptionsItemSelected(item);
	}

	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);// 去掉标题栏
		setContentView(R.layout.knowledge_list); // 软件activity的布局
		ActivityStackControlUtil.add(this);
		initComponent();
	}

	private class TextItemOnClickListener implements OnClickListener {
		private String url;
		private String title;
		private String type;

		public TextItemOnClickListener(String url, String title, String type) {
			this.url = url;
			this.title = title;
			this.type = type;
		}

		public void onClick(View v) {
			Intent intent = new Intent();
			intent.setClass(getApplicationContext(),KnowledgeDetailActivity.class);
			intent.putExtra("url", url);
			intent.putExtra("title", title);
			intent.putExtra("header", type);
			startActivity(intent);
		}

	}

	protected void onDestroy() {
		super.onDestroy();
		service.closeDB();
        ActivityStackControlUtil.remove(this);
	}
}